package com.chencq.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CorsFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		// 允许跨域访问的域，可以是一个域的列表
		response.setHeader("Access-Control-Allow-Origin", "*");
		// 是否允许请求带有验证信息,默认true
		response.setHeader("Access-Control-Allow-Credentials", "true");
		// 缓存此次请求的秒数。在这个时间范围内，所有同类型的请求都将不再发送预检请求而是直接使用此次返回的头作为判断依据，非常有用，大幅优化请求次数
		response.setHeader("Access-Control-Max-Age", "3600");
		// 允许使用的请求方法，以逗号隔开
		response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		// 允许自定义的头部，以逗号隔开，大小写不敏感
		response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");

		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}
